package com.auoem.radio;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.auctus.am.framework.constants.AmConstants;
import com.auctus.am.framework.entity.ChannelInf;
import com.auctus.am.framework.imp.HlThreadPoolManager;
import com.auctus.am.framework.imp.RadioManager;
import com.auctus.am.framework.interfaces.ComCallback;
import com.auctus.am.framework.tasks.RadioTaskManager;
import com.auctus.am.framework.tasks.SwitchChannelTask;
import com.auctus.am.framework.utils.LogM;
import com.auoem.radio.base.BaseActivity;
import com.auoem.radio.base.OemApplication;
import com.auoem.radio.common.custview.ConfirmDialogFragment;
import com.auoem.radio.common.utils.ResourceUtils;
import com.auoem.radio.service.PttService;
import com.auoem.radio.ui.msg.MsgFragment;
import com.auoem.radio.ui.ptt.PttFragment;
import com.auoem.radio.ui.radio.RadioFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.Objects;

/**
 * 20240418  去除启动服务
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private final static int DELAY_CH_TIME = 800;
    MainViewModel viewModel;
    private ConfirmDialogFragment mConfirmDialog;
    Handler mHandler;

    private int chId;

    private TextView tvCh;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvCh = findViewById(R.id.tvChId);
        mHandler = new Handler();
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_ptt, R.id.navigation_channel, R.id.navigation_msg, R.id.navigation_radio)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        NavigationUI.setupWithNavController(navView, navController);
        Objects.requireNonNull(MainActivity.this.getSupportActionBar()).setElevation(0);
//        viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
//        viewModel.mTitle.observe(this, new Observer<String>() {
//            @Override
//            public void onChanged(String s) {
//                LogM.d("viewModel on Main", "onChange: " + s);
//                MainActivity.this.getSupportActionBar().setTitle(s);
//            }
//        });

        ViewModelProvider.AndroidViewModelFactory instance = ViewModelProvider.AndroidViewModelFactory.getInstance(OemApplication.getApplication());
        viewModel = new ViewModelProvider(this, instance).get(MainViewModel.class);
        viewModel.mTitle.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                LogM.d("viewModel on Main", "onChange: " + s);
                MainActivity.this.getSupportActionBar().setTitle(s);
            }
        });

    }

    private Intent startService;

    @Override
    protected void onResume() {
        super.onResume();
        //启动这个服务
        startService = new Intent(getApplication(), PttService.class);
        //startService(startService);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //startForegroundService(startService);
        } else {
            startService(startService);
        }
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        mHandler.removeCallbacks(delayChangeChRun);
    }

    @Override
    public void onClick(View v) {
        LogM.d("MainActivity", "onclick: " + v.getTag());
        Fragment navFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        Fragment curFragment = navFragment.getChildFragmentManager().getPrimaryNavigationFragment();
        if (curFragment instanceof PttFragment) {
            ((PttFragment) curFragment).onClick(v);
        } else if (curFragment instanceof RadioFragment) {
            ((RadioFragment) curFragment).onClick(v);
        } else if (curFragment instanceof MsgFragment) {
            ((MsgFragment) curFragment).onClick(v);
        }
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        LogM.d(TAG, "onKeyUp: " + keyCode);
        switch (keyCode) {
//            case AmConstants
//                    .AM_KEY_CODE_CH_UP://285  24
            case AmConstants.AM_KEY_CODE_CH_UP:
                doOnChangeCh(true);
                return true;
            case AmConstants
                    .AM_KEY_CODE_CH_DOWN://286
                doOnChangeCh(false);
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        showCloseConfirm();
    }

    private void showCloseConfirm() {
        if (mConfirmDialog == null) {
            mConfirmDialog = new ConfirmDialogFragment();
        }
        mConfirmDialog.setOnConfirmListener(new ConfirmDialogFragment.OnConfirmListener() {
            @Override
            public void onConfirm(boolean isOk) {
                if (isOk) {
                    exit();
                }
            }
        });
        if (!mConfirmDialog.isAdded() && null == getSupportFragmentManager().findFragmentByTag("confirmClsDialog")) {
            mConfirmDialog.showNow(getSupportFragmentManager(), "confirmCloseDialog");
        }
        mConfirmDialog.setContent(ResourceUtils.getResourcesString(R.string.hl_main_exit_confirm));
    }

    /*Step-End.退出App前结束A6模块，否者可能影响App*/
    private void exit() {
        showProgress(R.string.hl_main_progress_exit);
        HlThreadPoolManager.getInstance().execut("exit", new Runnable() {
            @Override
            public void run() {
                OemApplication.getApplication().doOnDestroy();
            }
        });
    }

    private void doOnChangeCh(boolean isNext) {
        chId = RadioManager.getInstance().getRadioData().selCirChId(isNext);
        updateCh(chId, true);
        mHandler.removeCallbacks(delayChangeChRun);
        mHandler.postDelayed(delayChangeChRun, DELAY_CH_TIME);
    }

    private void updateCh(int chId, boolean isShow) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvCh.setText((chId + 1) + "");
                tvCh.setVisibility(isShow ? View.VISIBLE : View.GONE);
            }
        });
    }

    Runnable delayChangeChRun = new Runnable() {
        @Override
        public void run() {
            updateCh(chId, false);
            switchCurChange(chId);
        }
    };


    private void switchCurChange(int index) {
        ChannelInf channelInf = RadioManager.getInstance().getRadioData().getChannelOnIndex(index);
        showProgress(ResourceUtils.getResourcesString(R.string.hl_ptt_switch_ch_id_progress, channelInf.channelId + 1));
        RadioTaskManager.getInstance().startSwitchChannelTask(RadioManager.getInstance().getRadioData(), index, new ComCallback<Boolean>() {
            @Override
            public void onCallback(Boolean isSucc, int code, String inf) {
                LogM.d(TAG, "setCurChange: index: %d  code: %d  msg: %s", index, code, inf);
                if (isSucc) {
//                    RadioManager.getInstance().getRadioData().setCurChannel(channelInf);
                    toastResultUI(ResourceUtils.getResourcesString(R.string.hl_ptt_switch_ch_id_complete_final, channelInf.channelId + 1));
//                    updateChInf();
//                    SPUtils.setLastChID(HlApplication.getApplication(), channelInf.channelId);
                } else if (code == SwitchChannelTask.CODE_STOP) {
                    //主动停止的任务，不处理
                } else if (code >= 2) {
//                    RadioManager.getInstance().getRadioData().setCurChannel(channelInf);
                    toastResultUI(ResourceUtils.getResourcesString(R.string.hl_ptt_switch_ch_id_complete_half, channelInf.channelId + 1));
//                    updateChInf();
                } else {
                    toastResultUI(R.string.am_common_exe_failure);
                }
            }
        });
    }

}
